#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080

int main() {
    int server_socket, new_socket;
    struct sockaddr_in server_addr, client_addr;
    char buffer[1024] = {0};

    // 创建套接字
    if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 将套接字绑定到指定的 IP 地址和端口
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("Bind failed");
        exit(EXIT_FAILURE);
    }

    // 监听连接
    if (listen(server_socket, 3) == -1) {
        perror("Listen failed");
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port %d...\n", PORT);

    while (1) {
        // 接受连接
        socklen_t client_addr_len = sizeof(client_addr);
        if ((new_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len)) == -1) {
            perror("Accept failed");
            exit(EXIT_FAILURE);
        }

        printf("Connection accepted from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

        // 在连接上进行多次消息交互
        while (1) {
            // 接收消息
            read(new_socket, buffer, sizeof(buffer));
            printf("Client: %s\n", buffer);

            // 发送消息
            printf("Server: ");
            fgets(buffer, sizeof(buffer), stdin);
            send(new_socket, buffer, strlen(buffer), 0);
        }

        // 关闭当前连接
        close(new_socket);
    }

    close(server_socket);
    return 0;
}
